<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class RaoVat extends AdminBackEndController {
    public function __construct() {
        parent::__construct();
        $this->load->library('mypaging');
        $this->load->model('repo/raovat_model', 'raovat_model');
    }

    private function intialPaging($option) {
        $this->mypaging->setCount($this->raovat_model->adminCountRaoVat($option));
        $this->mypaging->setLimit(RAO_VAT_LIMIT);
        $this->mypaging->setMainURL(admin_rao_vat_paging_url());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function index($pageIndex = 1) {
        $option = null;
        $pCase = $this->input->get('f', true);
        if($pCase!= false && $pCase=='trash'){
            $option = array(
                'a.active_flg'  => 0,
                'a.deleted_at'  => null,
                'c.deleted_at'  => null,
                'd.deleted_at'  => null
                );
        }
        if($this->role==ROLE_MOD){
            $option['c.id'] = $this->user_id;
        }
        $aCol = array(
            'a.id', 'a.title', 'a.slug', 'a.image', 'a.description', 'a.cate_id', 'a.place_id', 'a.view_time',
            'a.created_at', 'a.highlight_flg', 'a.active_flg', 'a.deleted_at', 'c.image_folder', 'c.full_name as user_full_name', 'c.role',
            'b.name as place_name', 'd.title as cate_title', 'd.slug as cate_slug'
            );
        $aData = array();
        $this->intialPaging($option);
        $offset = ($pageIndex - 1) * RAO_VAT_LIMIT;
        $aRaoVat = $this->raovat_model->adminPaging(RAO_VAT_LIMIT, $offset, $aCol, $option);
        $aData['pagingBar'] = $this->mypaging->getBar($pageIndex, array('f'=>$pCase));
        $aData['pageTitle'] = 'Rao vặt';
        $aData['aRaoVat']   = $aRaoVat;

        $this->load->model('repo/category_model', 'category_model');
        $aData['aParentCate']  = $this->category_model->getCategories();
        $aData['aRaoVatPlace'] = $this->raovat_model->getRaoVatPlace();
        $this->renderView('backend/admin/raovat/index', $aData);
    }

    public function countSearch($searchKey){
        $this->mypaging->setCount($this->raovat_model->countAdminSearchPaging($searchKey));
        $this->mypaging->setLimit(RAO_VAT_LIMIT);
        $this->mypaging->setMainURL(admin_rao_vat_search_paging_url());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function search($pageIndex=1){
        $searchKey = $this->input->get('s', true);
        $aCol = array(
            'a.id', 'a.title', 'a.slug', 'a.image', 'a.description', 'a.cate_id', 'a.place_id', 'a.view_time',
            'a.created_at', 'a.active_flg', 'a.deleted_at', 'c.image_folder', 'c.full_name as user_full_name', 'c.role',
            'b.name as place_name', 'd.title as cate_title', 'd.slug as cate_slug'
            );
        $aData = array();
        $this->countSearch($searchKey);
        $offset = ($pageIndex - 1) * RAO_VAT_LIMIT;
        $aRaoVat = $this->raovat_model->adminSearchPaging(RAO_VAT_LIMIT, $offset, $aCol, $searchKey);
        $aData['pagingBar'] = $this->mypaging->getBar($pageIndex, array('s'=>$searchKey));
        $aData['pageTitle'] = 'Tìm kiếm | Rao vặt';
        $aData['aRaoVat']   = $aRaoVat;
        $aData['searchkey'] = $searchKey;

        $this->load->model('repo/category_model', 'category_model');
        $aData['aParentCate']  = $this->category_model->getCategories();
        $aData['aRaoVatPlace'] = $this->raovat_model->getRaoVatPlace();

        $this->renderView('backend/admin/raovat/index', $aData);
    }

    public function initHighlightPaging($option){
        $this->mypaging->setCount($this->raovat_model->countStickyWidget($option));
        $this->mypaging->setLimit(RAO_VAT_LIMIT);
        $this->mypaging->setMainURL(admin_rao_vat_highlight_paging_url());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function getHighlight($pageIndex=1){
        $option = null;
        $pCase = $this->input->get('f', true);
        if($pCase!= false && $pCase=='trash'){
            $option = array(
                'a.active_flg'  => 0,
                'a.deleted_at'  => null,
                'c.deleted_at'  => null,
                'd.deleted_at'  => null
                );
        }
        $aCol = array(
            'a.id', 'a.title', 'a.slug', 'a.image', 'a.description', 'a.cate_id', 'a.place_id', 'a.view_time',
            'a.created_at', 'a.active_flg', 'a.deleted_at', 'c.image_folder', 'c.full_name as user_full_name', 'c.role',
            'b.name as place_name', 'd.title as cate_title', 'd.slug as cate_slug'
            );
        $aData = array();
        $this->initHighlightPaging($option);
        $offset = ($pageIndex - 1) * RAO_VAT_LIMIT;
        $aRaoVat = $this->raovat_model->getStickyWidget(RAO_VAT_LIMIT, $offset, $aCol, $option);
        $aData['pagingBar'] = $this->mypaging->getBar($pageIndex, array('f'=>$pCase));
        $aData['pageTitle'] = 'Rao vặt';
        $aData['aRaoVat']   = $aRaoVat;

        $this->load->model('repo/category_model', 'category_model');
        $aData['aParentCate']  = $this->category_model->getCategories();
        $aData['aRaoVatPlace'] = $this->raovat_model->getRaoVatPlace();
        $this->renderView('backend/admin/raovat/index', $aData);
    }

    public function get($slug) {
        $this->load->helper('file');
        $aSelect = array('a.id, a.user_id, a.title, a.image', 'a.slug', 'a.cate_id', 'a.place_id', 'a.description',
            'a.detail', 'a.custom_info', 'a.active_flg', 'a.deleted_at, c.image_folder');
        $raoVat = $this->raovat_model->getSingleBySlug($slug, $aSelect, true);
        if ($raoVat == null || count($raoVat) == 0) {
            show_404();
        }
        if($raoVat->custom_info!=''){
            $oInfo = json_decode($raoVat->custom_info);
            $raoVat->user    = $oInfo->user;
            $raoVat->company = $oInfo->company;
            $raoVat->address = $oInfo->address;
            $raoVat->phone   = $oInfo->phone;
            $raoVat->email   = $oInfo->email;
            $raoVat->skype   = $oInfo->skype;
        } else {
            $raoVat->user    = null;
            $raoVat->company = null;
            $raoVat->address = null;
            $raoVat->phone   = null;
            $raoVat->email   = null;
            $raoVat->skype   = null;
        }
        $raoVatPlace = $this->raovat_model->getRaoVatPlace();
        $this->load->model('repo/category_model', 'cate_model');
        $raoVatCate = $this->cate_model->getCategories();
        $aData = array(
            'pageTitle' => $raoVat->getTitle(),
            'oRaoVat' => $raoVat,
            'aRaoVatPlace' => $raoVatPlace,
            'aRaoVatCate' => $raoVatCate,
            'action' => 'update',
            'action_link' => admin_page_url(RAOVAT_SLUG . '/cap-nhat'));
        $this->renderView('backend/admin/raovat/single', $aData);
    }

    public function insert() {
        $this->load->helper('file');
        $raoVat = new RaoVat_Entity();
        $raoVat->setTitle('Thêm mới');
        $raoVat->setUserId($this->user_id);
        $raoVat->setActiveFlg(1);
        $raoVat->user    = null;
        $raoVat->company = null;
        $raoVat->address = null;
        $raoVat->phone   = null;
        $raoVat->email   = null;
        $raoVat->skype   = null;
        $raoVat->image   = null;
        $raoVat->image_folder = $this->image_folder;
        $raoVatPlace = $this->raovat_model->getRaoVatPlace();
        $this->load->model('repo/category_model', 'cate_model');
        $raoVatCate = $this->cate_model->getCategories();
        $aData = array(
            'pageTitle' => 'Thêm mới',
            'oRaoVat' => $raoVat,
            'aRaoVatPlace' => $raoVatPlace,
            'aRaoVatCate' => $raoVatCate,
            'action' => 'insert',
            'action_link' => admin_page_url(RAOVAT_SLUG . '/them-moi'));
        $this->renderView('backend/admin/raovat/single', $aData);
    }

    public function doInsert() {
        $aResult     = array();
        $raovat      = $this->input->post('raovat', true);
        $raoVat_temp = $this->input->post('raovat');
        $custom_info = $this->input->post('u', true);
        $this->form_validation->set_rules('raovat[title]', 'lang:raovat_title', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('raovat[slug]', 'lang:raovat_slug', 'trim|required|callback_slug_check|xss_clean');
        if(isset($custom_info['custom_info_flg']) && $custom_info['custom_info_flg']==1){
            $this->form_validation->set_rules('u[user]',    'lang:info_user',     'trim|required|xss_clean');
            $this->form_validation->set_rules('u[company]', 'lang:info_company',  'trim|max_length[100]|xss_clean');
            $this->form_validation->set_rules('u[address]', 'lang:info_address',  'trim|required|max_length[160]|min_length[10]|xss_clean');
            $this->form_validation->set_rules('u[phone]',   'lang:info_phone',    'trim|required|numeric|max_length[15]|min_length[8]|xss_clean');
            //$this->form_validation->set_rules('u[email]',   'lang:info_email',    'trim|required|valid_email|xss_clean');
            $this->form_validation->set_rules('u[skype]',   'lang:info_skype',    'trim|max_length[50]|xss_clean');
        }
        $this->form_validation->set_rules('raovat[description]', 'lang:raovat_description', 'trim|required|xss_clean');
        $this->form_validation->set_rules('raovat[detail]',      'lang:raovat_detail',      'trim|required');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            $this->renderJSON($aResult);
            return;
        }

        //set detail
        $raovat['detail'] = $raoVat_temp['detail'];

        //set custom user post if exist
        if(isset($custom_info['custom_info_flg']) && $custom_info['custom_info_flg']==1){
            $raovat['custom_info'] = json_encode($custom_info);
            unset($custom_info['custom_info_flg']);
        } else {
            $raovat['custom_info'] = NULL;
        }

        //set image
        if(isset($raovat['image']) && $raovat['image']!=''){
            if (strpos($raovat['image'], TEMP_FOLDER_URL) !== false) {
                $this->load->library('MyImage', 'myimage');
                $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, RAOVAT_IMAGE_URL, $raovat['image']);
            } else if(strpos($raovat['image'], RAOVAT_IMAGE_URL) !== false){
                $a = explode('/', $raovat['image']);
                if(count($a)==2){
                    $raovat['image'] = $a[1];
                } else {
                    $raovat['image'] = NULL;
                }
            } else {
                $raovat['image'] = NULL;
            }
        } else {
            $raovat['image'] = NULL;
        }

        $raovat['updated_at'] = NULL;
        $raovat['deleted_at'] = NULL;
        $raovat['created_at'] = get_current_date();
        $raovat['user_id']    = $this->user_id;

        $result = $this->raovat_model->insert($raovat);
        if (!$result) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul><li>' . $this->lang->line('system_error') . '</li></ul>'
                );
        } else {
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('insert_success'),
                'href' => admin_raovat_single_url($raovat['slug'])
                );
        }
        $this->renderJSON($aResult);
    }

    public function doUpdate() {
        $aResult     = array('code'=>0, 'title'=>$this->lang->line('system_error'));
        $raovat      = $this->input->post('raovat', true);
        $raoVat_temp = $this->input->post('raovat');

        if(isset($raovat['update_case'])){
            //get id
            $id = isset($raovat['id']) && $raovat['id']!='' ? $this->encrypt->decode($raoVat_temp['id']) : false;
            if($id!=false && isset($raovat['update_case'])){
                unset($raovat['id']);
                if($raovat['update_case'] == UPDATE_FULL){
                    unset($raovat['update_case']);
                    $aResult = $this->fullUpdate($id, $raovat, $raoVat_temp);
                } else {
                    unset($raovat['update_case']);
                    $aResult = $this->flashUpdate($id, $raovat);
                }
            }
        }
        $this->renderJSON($aResult);
    }

    public function flashUpdate($id, $raovat) {
        $aResult = array('code'=>0, 'title'=>$this->lang->line('system_error'));
        $date = get_current_date();
        $data = array();
        $aResult = array();

        if(isset($raovat['active_flg'])) {
            if($raovat['active_flg'] == 0 || $raovat['active_flg'] == 1) {
                $data['active_flg'] = $raovat['active_flg'];
                $data['updated_at'] = $date;
            }
        }

        if(isset($raovat['delete_flg'])) {
            if ($raovat['delete_flg']==1){
                $data['deleted_at'] = $date;
            } elseif ($raovat['delete_flg']==0){
                $data['deleted_at'] = NULL;
                $data['updated_at'] = $date;
            }
        }

        if(isset($raovat['highlight_flg'])) {
            if ($raovat['highlight_flg']==1 || $raovat['highlight_flg']==0){
                $data['highlight_flg'] = $raovat['highlight_flg'];
                $data['updated_at'] = $date;
            }
        }

        $result = $this->raovat_model->update($id, $data);
        if($result){
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('update_success')
                );
        }
        return $aResult;
    }

    public function fullUpdate($id, $raovat, $raoVat_temp) {
        $this->form_validation->set_rules('raovat[title]',       'lang:raovat_title',       'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('raovat[slug]',        'lang:raovat_slug',        'trim|required|callback_slug_check|xss_clean');
        $this->form_validation->set_rules('raovat[description]', 'lang:raovat_description', 'trim|required|xss_clean');

        //Get details
        $raovat_detail = $this->input->post('raovat_detail');
        if($raovat_detail!=false){
            $this->form_validation->set_rules('raovat_detail',      'lang:raovat_detail',      'trim|required');
        }

        $custom_info = $this->input->post('u', true);
        if($custom_info!=false && isset($custom_info['custom_info_flg']) && $custom_info['custom_info_flg']==1){
            $this->form_validation->set_rules('u[user]',    'lang:info_user',     'trim|required|xss_clean');
            $this->form_validation->set_rules('u[company]', 'lang:info_company',  'trim|max_length[100]|xss_clean');
            $this->form_validation->set_rules('u[address]', 'lang:info_address',  'trim|required|max_length[160]|min_length[10]|xss_clean');
            $this->form_validation->set_rules('u[phone]',   'lang:info_phone',    'trim|required|numeric|max_length[15]|min_length[8]|xss_clean');
            //$this->form_validation->set_rules('u[email]',   'lang:info_email',    'trim|required|valid_email|xss_clean');
            $this->form_validation->set_rules('u[skype]',   'lang:info_skype',    'trim|max_length[50]|xss_clean');
        }
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            return $aResult;
        }

        //if change image must check for owner folder
        $curRaoVat = $this->raovat_model->getSingleById($id, array('a.id, a.user_id'), true);
        $isOwner = $curRaoVat->getUserId()==$this->user_id?true:false;

        //set image
        if($isOwner) {
            if(isset($raovat['image']) && $raovat['image']!=''){
                $imageInfo = explode('/', $raovat['image']);
                if(count($imageInfo)==2){
                    if ($imageInfo[0] == 'temp') {
                        $this->load->library('MyImage', 'myimage');
                        $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, RAOVAT_IMAGE_URL, $imageInfo[1]);
                    }
                    $raovat['image'] = $imageInfo[1];
                } else {
                    $raovat['image'] = NULL;
                }
            }
        }

        //set custom user post if exist
        if(isset($custom_info['custom_info_flg'])){
            if($custom_info['custom_info_flg']==1){
                $raovat['custom_info'] = json_encode($custom_info);
            } else {
                $raovat['custom_info'] = null;
            }
            unset($custom_info['custom_info_flg']);
        } else {
            $raovat['custom_info'] = null;
        }

        //set active flag
        if(isset($raovat['active_flg'])){
            if($raovat['active_flg'] == 1){
                $raovat['active_flg'] = 1;
            } else {
                $raovat['active_flg'] = 0;
            }
        } else {
            $raovat['active_flg'] = 0;
        }

        //set updated, deleted
        $date = get_current_date();
        if(isset($raovat['delete_flg'])){
            if($raovat['delete_flg']==1){
                $raovat['deleted_at'] = $date;
            } else {
                $raovat['deleted_at'] = null;
                $raovat['updated_at'] = $date;
            }
            unset($raovat['delete_flg']);
        } else {
            $raovat['deleted_at'] = null;
            $raovat['updated_at'] = $date;
        }
        if($raovat_detail!=false){
            $raovat['detail'] = $raovat_detail;
        }
        $result = $this->raovat_model->update($id, $raovat);
        if (!$result) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error')
                );
        } else {
            $aResult = array(
                'code'       => 1,
                'text'       => $this->lang->line('update_success'),
                'href'       => admin_raovat_single_url($raovat['slug']),
                'front_href' => rao_vat_single_url($raovat['slug']),
                'cmd_case'   => 'update'
                );
        }
        return $aResult;
    }
}
?>